package com.calvin.study.service.sys.security;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import com.calvin.study.config.security.jwt.JwtTokenUtil;
import com.calvin.study.exception.CustomException;
import com.calvin.study.exception.CustomExceptionType;

import javax.annotation.Resource;

@Service
public class JwtAuthService {

	@Resource
	AuthenticationManager authenticationManager;

	@Resource
	UserDetailsService userDetailsService;

	@Resource
	JwtTokenUtil jwtTokenUtil;

	/**
	 * 登录认证换取JWT令牌
	 * 
	 * @return JWT
	 */
	public String login(String username, String password) throws CustomException {
		//1.完成登录认证
		try {
			UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
			Authentication authentication = authenticationManager.authenticate(upToken);
			SecurityContextHolder.getContext().setAuthentication(authentication);
		} catch (AuthenticationException e) {
			throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "用户名或者密码不正确");
		}
		//2.加载用户和角色权限信息
		UserDetails userDetails = userDetailsService.loadUserByUsername(username);
		//3.生成jwt令牌
		return jwtTokenUtil.generateToken(userDetails);
	}

	/**
	 * @Title: refreshToken   
	 * @Description:  刷新token
	 * @date: 2022年5月20日 下午4:43:53   
	 * @version:
	 * @param oldToken
	 * @return          
	 * @throws
	 */
	public String refreshToken(String oldToken) {
		if (!jwtTokenUtil.isTokenExpired(oldToken)) {
			return jwtTokenUtil.refreshToken(oldToken);
		}
		return null;
	}

}
